import axios from 'axios'
import { Row } from 'element-ui';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
export default {
    /**
     * 生成国际化文件
    */
    CreatProperties(options: any){
        console.log(options);
        // 文件名 国际化
        let properties = ``;
        let json = {};
        properties += options.global.page + '=' + this.ch2Unicdoe(options.global.pageZh);

        // 页面中存在的组件数组
        let myTableArray:any = [];
        let myFormsArray:any = [];
        let myTabsArray:any = [];

        let lcb = document.getElementById("wrapper")?.querySelectorAll(".layout-components-box");
        lcb?.forEach(element => {
            let comType = (element as any).dataset.componentstype;
            let whichId = "";
            if(comType == 'table'){
                whichId = (element as any).dataset.tablewhich;
                myTableArray.push(this.FindArrayObject(whichId, options.tableArray));
            }else if(comType == 'form'){
                whichId = (element as any).dataset.formwhich;
                myFormsArray.push(this.FindArrayObject(whichId, options.formArray));
            }else if(comType == 'tabs'){
                whichId = (element as any).dataset.tabswhich;
                myTabsArray.push(this.FindArrayObject(whichId, options.tabsArray));
            }
        });

        myTableArray.forEach((element:any) => {
            element.columns && element.columns.forEach((col:any) => {
                (json as any)[col.prop] = col.label;
            });
        });

        myFormsArray.forEach((element:any) => {
            element.forms && element.forms.forEach((col:any) => {
                (json as any)[col.field] = col.label;
            });
        });

        myTabsArray.forEach((element:any) => {
            element.tabs.forEach((tab:any) => {
                ;(json as any)[tab.tabsPorp] = tab.tabsLabel;
                tab.columns && tab.columns.forEach((col:any) => {
                    (json as any)[col.prop] = col.label;
                });
            });
        });
        
        for(let key in json){
            properties += `
${key}=${this.ch2Unicdoe((json as any)[key])}`;
        }
        return properties;
    },
    /**
     * html to xml
    */
    HtmlToXml(options: any) {
        console.log(options)
        let pageType:string = options.global.pageType; // 页面类型
        let xml:object = {
            pages: {
                [pageType]: {}
            }
        }
        let pages = (xml as any).pages[pageType];
            pages._id = options.global.page;
            pages._title = options.global.page;
            pages._entityClass = options.global.entityClass;
            options.global.mainEntrance && (pages._mainEntrance = options.global.mainEntrance);
            options.global.width &&(pages._width = options.global.width);
            options.global.height &&(pages._height = options.global.height);
            options.global.autoQuery && (pages._autoQuery = options.global.autoQuery);
            options.global.onClose &&(pages._onClose = options.global.onClose);

        let addTableColumns = (target:[], obj?: object)=>{
            let doms = document.querySelector("div.layout-components-box[data-componentstype='table']");
            if(!doms) {
                return false;
            }
            let comType = (doms as any).dataset.componentstype;
            let whoWhich = (doms as any).dataset[comType+"which"];
            let array = this.FindArrayObject(whoWhich, options[comType+'Array']);
            if(obj){
                (obj as any).datasource = `<![`+array.keywordsTextareaHsql+`]]`;
                (obj as any)._entityClass = array.entityClass;
                (obj as any)._autoQuery = array.autoQuery || true;
            }
            array.columns.forEach((element: any) => {
                let obj:object = {
                    _id: element.prop,
                    _title: element.prop,
                    _dataType: element.dataType,
                    _horizonAlign: element.horizonAlign,
                    _sortable: element.sortable,
                    _verticalAlign: element.verticalAlign,
                    _visible: element.visible,
                    _language: element.language
                };
                // 如果不存在就不添加属性
                element.width && ((obj as any)._width = element.width);
                element.format && ((obj as any)._format = element.format);
                element.formatParam && ((obj as any)._formatParam = element.formatParam);
                // 添加obj
                (target as any).push(obj);
            });
            
        }

        let addForms = (target:{})=>{
            let doms = document.querySelector("div.layout-components-box[data-componentstype='form']");
            console.log(doms);
            if(!doms) {
                return false;
            }
            let comType = (doms as any).dataset.componentstype;
            let whoWhich = (doms as any).dataset[comType+"which"];
            let array = this.FindArrayObject(whoWhich, options[comType+'Array']);
            
            (target as any).hidden._id = array.hidden.id;
            (target as any).hidden._reserve = array.hidden.reserve;
            (target as any).hidden._title = array.hidden.title;
            array.forms.forEach((element:any) => {
                (target as any)[element.type] ? null : (target as any)[element.type] = [];
                let obj:any = {
                    eventListeners: "",
                    visibleExpression: "",
                    _id: element.field,
                    _title: element.field,
                    _col: element.col,
                    _row: element.row,
                    _span: element.span,
                    _focusUI: element.focusUI,
                    _forceOverride: element.forceOverride,
                    _inVisible: element.inVisible,
                    _readOnly: element.readOnly,
                    _required: element.required,
                    _reserve: element.reserve,
                    _trimSpace: element.trimSpace,
                };
                element.hsql && (obj.dataValue = `<![CDATA[`+element.hsql+']]');
                !element.hsql && (obj.hql = "");
                element.displayColumn && (obj._displayColumn = element.displayColumn);
                element.displayedTableHead && (obj._displayedTableHead = element.displayedTableHead);
                element.language && (obj._language = element.language);
                element.manualEditable && (obj._manualEditable = element.manualEditable);
                element.multiple && (obj._multiple = element.multiple);
                element.percentSignPosition && (obj._percentSignPosition = element.percentSignPosition);
                element.manualEditable && (obj._manualEditable = element.manualEditable);
                element.defaultCurrentDate && (obj._defaultCurrentDate = element.defaultCurrentDate);
                (target as any)[element.type].push(obj);
            });
        }
        
        let addTabs = (detail: []) => {
            let doms = document.querySelector("div.layout-components-box[data-componentstype='tabs']");
            console.log(doms);
            if(!doms) {
                return false;
            }
            let comType = (doms as any).dataset.componentstype;
            let whoWhich = (doms as any).dataset[comType+"which"];
            let array = this.FindArrayObject(whoWhich, options[comType+'Array']);
            array.tabs.forEach((element:any) => {
                let obj = {
                    datasource: "",
                    columns: {column: []}
                };
                (obj as any).datasource = element.keywordsTextareaHsql;
                (obj as any)._tabId = element.id;
                (obj as any)._entityClass = element.entityClass;
                (obj as any)._autoQuery = element.autoQuery;
                //  = element.columns;
                // element.columns []
                element.columns.forEach((ele:any) => {
                    let objKids:object = {
                        _id: ele.prop,
                        _title: ele.prop,
                        _dataType: ele.dataType,
                        _horizonAlign: ele.horizonAlign,
                        _sortable: ele.sortable,
                        _verticalAlign: ele.verticalAlign,
                        _visible: ele.visible,
                        _language: ele.language
                    };
                    // 如果不存在就不添加属性
                    ele.width && ((objKids as any)._width = ele.width);
                    ele.format && ((objKids as any)._format = ele.format);
                    ele.formatParam && ((objKids as any)._formatParam = ele.formatParam);
                    (obj as any).columns.column.push(objKids);
                });

                detail.push(obj as never);
            });
        }

        if(pageType == "maintainPage"){
            // maintain页面
            pages.workflow = options.global.workflow;
            pages.datasource = `<![CDATA[${options.global.datasource}]]`;
            pages.columns = { column: [] }
            // 添加table数据
            addTableColumns(pages.columns.column);
        }else if(pageType == "editPage"){
            // edit页面
            pages.workflow = options.global.workflow;
            pages.initListeners = "";
            pages.inputUIs = {hidden:{}}
            addForms(pages.inputUIs);
        }else if(pageType == "modifyDetailPage"){
            pages.initListeners = options.global.initListeners;
            pages.modify = {inputUIs: {hidden:{}}}
            pages.detail = {
                datasource: "",
                _entityClass: "",
                _autoQuery: "",
                columns: {column: []}
            }
            addForms(pages.modify.inputUIs);
            addTableColumns(pages.detail.columns.column, pages.detail);
        }else if(pageType == "modifyMultiDetailPage"){
            pages.initListeners = options.global.initListeners;
            pages.modify = {inputUIs: {hidden:{}}}
            pages.details = {
                detail:[]
            }
            addForms(pages.modify.inputUIs);
            addTabs(pages.details.detail);
        }
        return '<?xml version="1.0" encoding="UTF-8"?>'+options.js2xml(xml);
        // let div = document.createElement("div");
        // // 页面设置
        // let onClose = options.global.onClose ? `onClose="${options.global.onClose}"` : ``;
        // let mainEntrance:any = pageType == 'maintainPage' ? `mainEntrance="true"` : ``;
        // let width:any = options.global.width;
        // let height:any = options.global.height;
        // width = width == 0 ? `` : `width="${width}"`;
        // height = height == 0 ? `` : `height="${height}"`;
        
        // div.innerHTML = options.html;
        // div.querySelectorAll(".drag-tools-bar").forEach(element => {
        //     element.remove();
        // });

        // let tableXML = ``;
        // let formXML = ``;
        // let tabsXML = ``;
        
        // // 生成table xml
        // var createTable = (array:object)=>{
        //     let tbXml = ``;
        //     (array as any).columns.forEach((element: any) => {
        //         let TableWidth = element.width ? `width="${element.width}"` : '';
        //         let Format = element.format ? `format="${element.format}"` : '';
        //         let FormatParam = element.formatParam ? `formatParam="${element.formatParam}"` : '';
        //         tbXml += `
        //         <column id="${element.prop}" title="${element.prop}" visible="${element.visible}" sortable="${element.sortable}" horizonAlign="${element.horizonAlign}" verticalAlign="${element.verticalAlign}" dataType="${element.dataType}" ${Format} ${FormatParam} ${TableWidth}/>`;
        //     });
        //     let ct = `
        //     <datasource><![CDATA[${(array as any).keywordsTextareaHsql}
        //     ]]></datasource>
        //     <columns>
        //     ${tbXml}
        //     </columns>`;
        //     return ct;
        // }

        // // 生成form 
        // var createForm = (array: object) => {
        //     let tbXml = ``;
        //     (array as any).forms.forEach((element: any) => {
        //         console.log(element.type == "remote")
        //         let hb = element.type == "remote" ? `multiple="${element.multiple}" manualEditable="${element.manualEditable}" displayColumn="${element.displayColumn}" percentSignPosition="${element.percentSignPosition}" displayedTableHead="${element.displayedTableHead}"` : ``;
        //         let defaultCurrentDate = element.type == "date" ? `defaultCurrentDate="${element.defaultCurrentDate}"` : ``;
        //         let hql = element.type == "remote" ? `<hql><![CDATA[
        //             ${element.hsql}   
        //             ]]></hql>` : `<hql/>`;
        //         tbXml += `
        //         <${element.type} id="${element.field}" title="${element.field}" row="${element.row}" col="${element.col}" span="${element.span}" readOnly="${element.readOnly}" required="${element.required}" reserve="${element.reserve}" forceOverride="${element.forceOverride}" focusUI="${element.focusUI}" inVisible="${element.inVisible}" ${defaultCurrentDate} ${hb}>
        //             <visibleExpression/>
        //             ${hql}
        //             <eventListeners/>
        //         </${element.type}>`;
        //     });
        //     let ct = `
        //     <inputUIs>
        //         <hidden id="w.id" title="w.id" reserve="false"/>
        //         ${tbXml}
        //     </inputUIs>`;
        //     return ct;
        // }

        // var createTabs = (array: object) => {
        //     let tbXml = ``;
        //     (array as any).tabs.forEach((element:any) => {
        //         tbXml += `
        //     <detail tabId="${element.tabsPorp}" entityClass="com.vtradex.kms.model.account.verification.KmsFaUnVerficationRecord" autoQuery="true">${createTable(element)}
        //     </detail>
        //     `;
        //     });
        //     return tbXml;
        // }
        
        // div.querySelectorAll(".layout-components-box").forEach(element => {
        //     let comType = (element as any).dataset.componentstype;
        //     let whoWhich = (element as any).dataset[comType+"which"];
        //     let array = this.FindArrayObject(whoWhich, options[comType+'Array']);
        //     if(comType == "table"){
        //         if(pageType == "modifyDetailPage"){
        //             tableXML += `<detail>${createTable(array)}
        //     </detail>`;
        //         }else{
        //             tableXML += createTable(array);
        //         }
        //     }else if(comType == "form"){
        //         console.log(pageType)
        //         // modify modifyDetailPage modifyMultiDetailPage
        //         if(pageType == "modifyDetailPage" || pageType == "modifyMultiDetailPage"){
        //         formXML += `<modify>${createForm(array)}
        //     </modify>`;
        //         }else{
        //             formXML += createForm(array);
        //         }
        //     }else if(comType == "tabs"){
        //         tabsXML += `<details>${createTabs(array)}
        //     </details>`;
        //     }
        // });

        // console.log(options)
        // let xml = `<?xml version="1.0" encoding="UTF-8"?>
        // <pages>
        // <${pageType} id="${options.global.page}" title="${options.global.page}" autoQuery="${options.global.autoQuery}" entityClass="${options.global.entityClass}" ${onClose} ${mainEntrance} ${width} ${height}>
        //     <workflow/>
        //     <initListeners></initListeners>
        //     ${formXML}
        //     ${tabsXML}
        //     ${tableXML}
        // </${pageType}>
        // </pages>`;
        // return xml;
    },
    /**
     * 纯HTML内容
    */
    OnlyHtmlValue(options: any){
        return options.html;
    },
    /**
     * 根据条件查特定dom
    */
    GetDom(condition:string){
        return document.querySelector(condition);
    },
    /**
     * 查询input前面的宽度之和
     * array:[] 查询数组, object: object数组查询对象
    */
    GetInputFrontWidth(array:[], object: object){
        let span = 0;
        for (const iterator of array) {
            if(iterator['field'] == (object as any)['field']){
                break;
            }
            if(iterator['row'] == (object as any)['row']){
                span += iterator['span'];
            }
        }
        return span;
    },
    /**
     * 二维数组排序
    */
    SortArrayTwoDimensional(array: []){
        return array.sort((a, b)=>{return a['col'] - b['col']}).sort((a, b)=>{return a['row'] - b['row']});
    },
    /**
     * 设置form尺寸
    */
    SetFormSize(object: object){
        // 获取最大row值
        let maxRow = 0;
        (object as any)['forms'].forEach((element:any) => {
            element.row >= maxRow ? maxRow = element.row : null;
        });
        let form = document.querySelector("div[data-formwhich=" + (object as any).id + "]")?.querySelector("form[data-type='form']");
        (form as any).style.height = ((maxRow-1) * 33 + (maxRow+1)*20) + 'px';
    },
	/**
     * 下载--无用--废弃
     */
    DownloadFile(name:string, type:string, url:string){
        var a = document.createElement('a');
        a.setAttribute("href", "data:text/properties;base64,"+url);
        a.setAttribute("download", name);
        if (document.createEvent) {
            var event = document.createEvent("MouseEvents");
            event.initEvent("click", true, true);
            a.dispatchEvent(event);
        } else {
            a.click();
        }
    },
	/**
     * axios请求封装
     */
    Axios: function (url:any, data:any, res:any, err:any) {
        axios.post(url, data).then(res, err)
    },
	/**
     * 通过关键字查找对象数组中相等的值 id
     */
    FindArrayObject(id:any, arr:any[]){
        let array:any = {};
        arr.forEach(element => {
            if(element.id == id){
                array = element;
            }
        });
        return array;
    },
	/**
     * 通过关键字查找对象数组中相等的值 field
     */
    FindArrayObjectForField(field:any, arr:any[]){
        let array:any = {};
        arr.forEach(element => {
            if(element.field == field){
                array = element;
            }
        });
        return array;
    },
    /**
     * 查询某个元素的祖先元素
    */
    FindAncestorsElement(currentDom:any, ancestorsClass:any){
        var result = [];
        let x = currentDom;
        while (x.tagName.toLocaleUpperCase() != 'BODY') {
            if(x.className.indexOf(ancestorsClass) >= 0){
                result = x;
                break;
            }
            x = x.parentNode;
        }
        return result;
    },
	/**
     * 检查布局框内容是否合法
     */
    CheckLayoutNum(txt:string){
        // 检查布局分割是否正确
        let numArr = txt.split("|")[1] !== "" ? txt.split("|")[1].split(' ') : [];
        let numbers = [];
        for(let key of numArr){
            !isNaN(parseInt(key)) ? numbers.push(parseInt(key)) : null;
        }
        let total = numbers.reduce((prev,current,index,arr)=>{
            return prev+current
        });
        if(total !== 100){
            return false;
        }else if(numbers.length == 0){
            return false;
        }else{
            return numbers;
        }
    },
    /**
     * 清除所有的虚线框
    */
    ClearEmptyFrame(){
        var doms = document.querySelectorAll(".empty-frame");
        doms.forEach((element: any) => {
            element.remove();
        });
    },
    InsertAfter(newElement:any, targentElement:any) {
        var parent = targentElement.parentNode;
        if (parent.lastChild == targentElement) {
            parent.appendChild(newElement);
        } else {
            parent.insertBefore(newElement, targentElement.nextSibling)
        }
    },
    /**
     * 插入并排序函数
    */
    InsertArrSort(numberX:number, numberY:number, array:object[], type:string) {
        let index:number = array.length;

        let returnType = 'y';

        if(type == 'input'){
            returnType = 'xy';
        }

        if(returnType == 'y'){
            for(let i=0;i<array.length;i++){
                if((array[i] as any)['y'] >= numberY){
                    index = i;
                    break;
                }
            }
        }else if(returnType == 'x'){
            for(let i=0;i<array.length;i++){
                if((array[i] as any)['x'] >= numberX){
                    index = i;
                    break;
                }
            }
        }else if(returnType == 'xy'){
            for(let i=0;i<array.length;i++){
                if((array[i] as any)['x'] >= numberX && (array[i] as any)['y'] >= numberY){
                    index = i;
                    break;
                }
            }
        }
        
        return index;
    },
    /**
     * 拖放到目标DOM并排序
     * e:原生对象
     * element:需要添加的拖动对象
    */
    WrapperOver(e:any, type:string, _this: object){
        this.ClearEmptyFrame();
        let target = (e as any).target; // 目标dom
        let targetOffsetY = (e as any).offsetY; // 目标dom中相对位置
        let targetOffsetX = (e as any).offsetX; // 目标dom中相对位置
        let childNodes = (e as any).target.childNodes; // 目标dom中的所有子节点
        let isOnInputCom = false; // 是否在文本组件框上
        
        if(type.indexOf("Layout") >= 0 && target.dataset.type !== "LayoutBox"){ 
            return false; 
        }else if(type.indexOf("Components") >= 0 ){
            if(type.indexOf("form") >= 0 && target.dataset.components !== "ComponentsBox"){
                return false;
            }
            if(type.indexOf("table") >= 0 && target.dataset.components !== "ComponentsBox"){
                return false;
            }
            if(type.indexOf("tabs") >= 0 && target.dataset.components !== "ComponentsBox"){
                return false;
            }
            if(type.indexOf("input") >= 0 && this.FindAncestorsElement(target, 'el-form form-box-drag').dataset && this.FindAncestorsElement(target, 'el-form form-box-drag').dataset.type !== "form"){
                return false;
            }else if(type.indexOf("input") >= 0 && this.FindAncestorsElement(target, 'el-form form-box-drag').dataset && this.FindAncestorsElement(target, 'el-form form-box-drag').dataset.type == "form"){
                if(this.FindAncestorsElement(target, 'el-form-item el-form-item--small') instanceof HTMLElement){
                    isOnInputCom = true;
                }else{
                    isOnInputCom = false;
                }
                target = this.FindAncestorsElement(target, 'el-form form-box-drag');
                childNodes = target.childNodes;
            }
        }else if(type.indexOf("WrapperBox") >= 0 && target.dataset.type !== "LayoutBox"){
            return false;
        }

        let emptyFrame = document.createElement("div");
        emptyFrame.className = "empty-frame";

        let topArr = [];
        let LeftArr = [];
        let potionsArr = [];
        for(let childDom of childNodes){
            let y = childDom.offsetTop + childDom.offsetHeight/2;
            let x = childDom.offsetLeft + childDom.offsetWidth/2;
            topArr.push(y);
            LeftArr.push(x);
            potionsArr.push({
                x: x,
                y: y
            });
        }
        let index = this.InsertArrSort(targetOffsetX, targetOffsetY, potionsArr, type.split('|')[1]);
        

        let targetArray:[] = [];
        
        if(type.split('|')[1] == 'input'){
            if(this.FindAncestorsElement(e.target, 'el-form form-box-drag').dataset && this.FindAncestorsElement(e.target, 'el-form form-box-drag').dataset.type == "form"){
                let father = this.FindAncestorsElement(e.target, 'layout-components-box');
                targetArray = this.FindArrayObject(father.dataset.formwhich, (_this as any)['formNumberArray']).forms;

                if(isOnInputCom){
                    let i = Array.from(childNodes).indexOf(this.FindAncestorsElement(e.target, 'el-form-item el-form-item--small'));
                    index = i;
                }

                if(targetArray.length == 0){
                    // 目标form为空，无数组
                }else{
                    
                }
                
                if(index == targetArray.length){
                    let targetDomInputList = father.querySelector("div[data-felid='"+(targetArray as any)[index-1]['field']+"']");
                    emptyFrame.style.top = (targetDomInputList.offsetTop - 20) + 'px';
                    emptyFrame.style.left = (targetDomInputList.offsetLeft + targetDomInputList.offsetWidth) + 'px';
                }else{
                    let targetDomInputList = father.querySelector("div[data-felid='"+(targetArray as any)[index]['field']+"']");
                    emptyFrame.style.top = (targetDomInputList.offsetTop - 20) + 'px';
                    emptyFrame.style.left = (targetDomInputList.offsetLeft) + 'px';
                }
            }else{
                return false;
            }
        }

        if(childNodes.length === 0){
            target.appendChild(emptyFrame);
        }else{
            if(index == childNodes.length){
                target.appendChild(emptyFrame)
            }else{
                target.insertBefore(emptyFrame, childNodes[index])
            }
        }

        return index;
    },
    ch2Unicdoe(str:string){
        if(!str){
            return "";
        }
        let unicode = '';
        let isChinese = (s:string) => {
            return /[\u4e00-\u9fa5]/.test(s);
        }
        for (let i=0; i<str.length; i++) {
            let temp = str.charAt(i);
            if(isChinese(temp)){
                unicode += '\\u' +  temp.charCodeAt(0).toString(16);
            }
            else{
                unicode += temp;
            }
        }
        return unicode;
    }
}